﻿#include "widget.h"
#include "ui_widget.h"
#include "registerui.h"

Widget* Widget::m_pWidget;
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->comboBox->installEventFilter(this);
    m_pWidget = nullptr;
    m_control_show = false;
    //下拉列表选中项改变时改变头像
    connect(this,&Widget::loadHead,this,[=](QString id){
        QString path = QCoreApplication::applicationDirPath();
        QString headurl = ChatDB::getInstance()->getImgUrl(id);
        if(headurl != "")
        {
            QString style = QString("min-width:  80px;max-width:  80px;min-height: 80px;max-height: 80px;border-radius: 40px;border-width: 1 1 1 1;border-image: url(%1) 0 0 0 0 stretch strectch;").arg(headurl);
            ui->label_3->setStyleSheet(style);
        }
        else
        {
            QString style = QString("min-width:  80px;max-width:  80px;min-height: 80px;max-height: 80px;border-radius: 40px;border-width: 1 1 1 1;border-image: url(res/Icon/joker.png) 0 0 0 0 stretch strectch;");
            ui->label_3->setStyleSheet(style);
        }
    });
    setShadow();
    beautification();
    loadUser();
    connect(&m_gradientTimer,&QTimer::timeout,this,&Widget::gradientBackGround);
    m_gradientTimer.start(100);
    m_pChatSocket = ChatSocket::getInstance();
    connect(m_pChatSocket,&ChatSocket::transMSG,this,&Widget::onTransMSG);
}

Widget::~Widget()
{
    delete ui;
    delete m_pChatSocket;
    delete m_AccountList;
    delete m_mapper;
}

Widget *Widget::getInstance()
{
    if(m_pWidget == nullptr)
        m_pWidget = new Widget;
    return m_pWidget;
}

QString Widget::getID()
{
    return m_id;
}

void Widget::fillUID(QString uid)
{
    ui->username->setText(uid);
    ui->pwd->setText("");
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton)
    {
        isPressedWidget = true; // 当前鼠标按下的是QWidget而非界面上布局的其它控件
        last = event->globalPos();
    }
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if (isPressedWidget)
    {
        int dx = event->globalX() - last.x();
        int dy = event->globalY() - last.y();
        last = event->globalPos();
        move(x()+dx, y()+dy);
    }
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    int dx = event->globalX() - last.x();
    int dy = event->globalY() - last.y();
    move(x()+dx, y()+dy);
    isPressedWidget = false; // 鼠标松开时，置为false
}

void Widget::setShadow()
{
    //设置无边框
    setWindowFlags(Qt::FramelessWindowHint);
    //设置窗体透明
    setAttribute(Qt::WA_TranslucentBackground, true);
    QGraphicsDropShadowEffect *shadow=new QGraphicsDropShadowEffect();
    shadow->setBlurRadius(15);//设置圆角半径
    shadow->setColor(QColor(0,0,0));//设置边框颜色
    shadow->setOffset(0,0);
    ui->MainWidget->setStyleSheet("background-color:white");
    ui->MainWidget->setGraphicsEffect(shadow);
}

void Widget::beautification()
{
    //加载图片图标
    ui->label_logo->setPixmap(QPixmap("res/Icon/joker.png"));
    ui->label_5->setPixmap(QPixmap("res/img/signatrue.png"));
    //添加系统托盘
    //加载系统托盘使用的图标
    QIcon icon = QIcon("res/Icon/joker.png");
    //设置图标
    m_trayIcon.setIcon(icon);
    //当鼠标悬浮，显示文字
    m_trayIcon.setToolTip("Joker");
    //显示此托盘
    m_trayIcon.show();
    //为托盘添加菜单项
    m_ac1.setText("打开主界面");
    m_ac2.setText("退出");
    m_menu.addAction(&m_ac1);
    m_menu.addSeparator();
    m_menu.addAction(&m_ac2);
    m_trayIcon.setContextMenu(&m_menu);
    //为两个菜单项添加槽
    connect(&m_ac1,&QAction::triggered,this,[=](){//托盘的显示响应
        if(!m_control_show)
            show();
        else {
            MainWidget::getInstance()->show();
        }
    });
    connect(&m_trayIcon,&QSystemTrayIcon::activated,[=](QSystemTrayIcon::ActivationReason reason){//为托盘添加双击显示功能
        if(reason == QSystemTrayIcon::DoubleClick)
        {
            if(!m_control_show)
                show();
            else {
                MainWidget::getInstance()->show();
            }
        }
    });
    connect(&m_ac2,&QAction::triggered,this,[=](){//托盘的退出响应
        close();
    });
    //为文本框添加图标
    m_ac3.setIcon(QIcon("res/Icon/joker.png"));
    ui->username->addAction(&m_ac3,QLineEdit::LeadingPosition);//添加到左侧
    m_ac4.setIcon(QIcon("res/Icon/lock.png"));
    ui->pwd->addAction(&m_ac4,QLineEdit::LeadingPosition);//添加到左侧
    m_ac5.setIcon(QIcon("res/Icon/keyboard.png"));
    ui->pwd->addAction(&m_ac5,QLineEdit::TrailingPosition);//添加到右侧
}

void Widget::gradientBackGround()
{
    static int a = 100;
    static int b = 240;
    static int c = 240;
    static int d = 100;
    QString qss = QString("background-color: qlineargradient(spread:pad,  x1:0, x2:1, y1:0, y2:1,  stop: 0 rgba(0,%1,%2,255),stop: 1 rgba(0,%3,%4,255));border: none;border-radius: 5px;color: rgb(255, 255, 255);").arg(a).arg(b).arg(c).arg(d);
    ui->label_4->setStyleSheet(qss);
    a+=5;c-=5;b-=5;d+=5;
    if(a>240)
    {
        a-=5;b+=5;c+=5;d-=5;
    }
    if(a<80)
    {
        a+=5;c-=5;b-=5;d+=5;
    }
}

void Widget::loadUser()
{
    QString path = QCoreApplication::applicationDirPath();
    QStringList slist = getAllDir(path);//获取所有用户文件目录
    QString imgUrl;//账户头像路径
    QString acountUrl;//账户配置文件路径
    QString id, pwd, nickName;//用户名,密码和昵称
    //将用户读取到列表
    m_mapper = new QSignalMapper(this);
    m_AccountList = new QListWidget(this);
    m_AccountList->setFocusPolicy(Qt::NoFocus);
    m_AccountList->setItemDelegate(new MyComboxDelegate);
    ui->comboBox->setModel(m_AccountList->model());
    ui->comboBox->setView(m_AccountList);
    int i = 0;
    for(auto str : slist)
    {
        QString userpath = QString("%1/%2").arg(path).arg(str);
        Json::Reader reader;
        Json::Value root;
        acountUrl = QString("%1/user.json").arg(userpath);
        QFile file(acountUrl);
        if(!file.open(QIODevice::ReadOnly))
        {
            qDebug()<<"[Widget::loadUser()]=>open file fail.\n";
            return;
        }
        QByteArray ba = file.readAll();
        QString con(ba);
        if(reader.parse(con.toStdString(),root))
        {
            id = root["id"].asCString();
            pwd = root["pwd"].asCString();
//            QString str = ChatDB::getInstance()->getImgUrl(id);
            imgUrl = ChatDB::getInstance()->getImgUrl(id);
//            imgUrl = QString("%1/%2").arg(path).arg(str);
//            imgUrl = str;
            nickName = ChatDB::getInstance()->getNickName(id);
            m_vecname.append(id);
            m_vecpwd.append(pwd);
        }
        file.close();
        QHBoxLayout *horLayout = new QHBoxLayout();//水平布局
        QLabel * label_info = new QLabel();
        label_info->setStyleSheet(QString("border-image: url(%1);border-radius:25px;").arg(imgUrl));
        label_info->setFixedSize(50,50);
        QString userinfo = QString("%1\n%2").arg(id).arg(nickName);
        QLabel * la2 = new QLabel(userinfo);
        QPushButton * b1 = new QPushButton();
        b1->setIcon(QIcon("res/Icon/delete.png"));
        b1->setFixedSize(50,50);
        b1->setIconSize(QSize(50,50));
        b1->setStyleSheet("QPushButton{background:transparent;border:none;}");
        connect(b1,SIGNAL(clicked(bool)),m_mapper,SLOT(map()));
        m_mapper->setMapping(b1,i);
        m_vector.append(i);
        horLayout->addWidget(label_info); //前面头像
        horLayout->addWidget(la2);//中间名字
        horLayout->addWidget(b1);//后面删除按钮
        QWidget *widget =new QWidget(this);
        widget->setLayout(horLayout);
        QListWidgetItem * Listitem = new QListWidgetItem();
        m_AccountList->addItem(Listitem);
        m_AccountList->setItemWidget(Listitem,widget);
        i++;
    }
    connect(m_mapper,QOverload<int>::of(&QSignalMapper::mapped),this,&Widget::deleteAccount);
}

QStringList Widget::getAllDir(const QString& dirPath)
{
    QStringList fileList;
    QDir dir(dirPath);
    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Dirs);
    foreach (auto fileInfo, fileInfoList)
    {
        if(fileInfo.isDir())
        {
            fileList.append(fileInfo.fileName());
        }
    }
    return fileList;
}

bool Widget::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == ui->comboBox)
    {
        if(event->type() == QEvent::MouseMove)
            return true;
    }
    return QWidget::eventFilter(obj,event);
}


void Widget::on_btn_close_clicked()
{
    close();
}

void Widget::on_btn_min_clicked()
{
    hide();
}

void Widget::on_btn_login_clicked()//登录
{
    QString id = ui->username->text();
    QString pwd = ui->pwd->text();
    m_id = id;
    if(id.isEmpty()&&pwd.isEmpty())
    {
        QMessageBox::warning(this,"警告","用户名或密码为空");
        return;
    }
    bool isSave;
    if(ui->checkBox->isChecked())
        isSave = true;
    else
        isSave = false;
    m_pChatSocket->onLogin(id,pwd,isSave);
}

void Widget::onTransMSG(MsgType type,QString msg)
{
    switch (type)
    {
    case MsgType::CONNECTED:
        ui->label_7->setStyleSheet("background-color:blue;");
        break;
    case MsgType::LOGINS:
    {
        m_trayIcon.setToolTip(msg);
        m_control_show = true;
        hide();
        break;
    }
    case MsgType::LOGINF:
        QMessageBox::critical(this,"提示",msg);
        break;
    case MsgType::ANSERS:
        break;
    case MsgType::ANSERF:
        break;
    case MsgType::REGISTERF:
        break;
    case MsgType::REGISTERS:
        break;
    case MsgType::RESETPWDS:
        break;
    }
}

void Widget::deleteAccount(int i)
{
    QString userDir;
    QMessageBox *message = new QMessageBox(QMessageBox::Question,tr("提示"), tr("是否要删除该账号信息\n请注意:当你选择是时,与此账号有关的所有记录都会被删除"), QMessageBox::Yes | QMessageBox::No,this);
    if(QMessageBox::Yes == message->exec())
    {
        userDir = QString("%1").arg(m_vecname[i]);
        ChatDB::getInstance()->deleteUserInfo(m_vecname[i]);
        m_vecname.removeAt(m_vector.indexOf(i));
        m_vecpwd.removeAt(m_vector.indexOf(i));
        //当前索引是否为删除对象，若是，则使用第一个
        if(m_vector.indexOf(i) == ui->comboBox->currentIndex())
        {
            if(m_vecname.length() != 0)
            {
                ui->comboBox->setCurrentIndex(0);
            }
        }
        if(m_vecname.length() == 0)
        {
            ui->username->setText("");
            ui->pwd->setText("");
            m_AccountList->item(0)->setHidden(true);
            QString headurl("res/Icon/joker2.png");
            QString style = QString("min-width:  80px;max-width:  80px;min-height: 80px;max-height: 80px;border-radius: 40px;border-width: 1 1 1 1;border-image: url(%1) 0 0 0 0 stretch strectch;").arg(headurl);
            ui->label_3->setStyleSheet(style);
            return;
        }
        //删除账号信息
        QListWidgetItem* item;
        item = m_AccountList->takeItem(m_vector.indexOf(i));
        m_AccountList->removeItemWidget(item);
        delete item;
        m_vector.erase(m_vector.begin()+m_vector.indexOf(i));
        //删除配置文件和聊天记录
        QString path = QCoreApplication::applicationDirPath();
        path += "/" + userDir;
        QDir dir;
        dir.setPath(path);
        dir.removeRecursively();
    }
}

void Widget::on_comboBox_currentIndexChanged(int index)
{
    ui->username->setText(m_vecname.at(index));
    ui->pwd->setText(m_vecpwd.at(index));
    // qDebug()<<m_vecname.at(index)<<m_vecpwd.at(index)<<endl;
    emit loadHead(ui->username->text());
}

void Widget::on_btn_reg_clicked()
{
    RegisterUI::getInstance()->show();
}

void Widget::on_username_editingFinished()
{
    QString id = ui->username->text();
//    QString path = QCoreApplication::applicationDirPath();
    QString headurl = ChatDB::getInstance()->getImgUrl(id);
    if(headurl != "")
    {
        QString style = QString("min-width:  80px;max-width:  80px;min-height: 80px;max-height: 80px;border-radius: 40px;border-width: 1 1 1 1;border-image: url(%1) 0 0 0 0 stretch strectch;").arg(headurl);
        ui->label_3->setStyleSheet(style);
    }
    else
    {
        QString style = QString("min-width:  80px;max-width:  80px;min-height: 80px;max-height: 80px;border-radius: 40px;border-width: 1 1 1 1;border-image: url(res/Icon/joker2.png) 0 0 0 0 stretch strectch;");
        ui->label_3->setStyleSheet(style);
    }
}
